const express = require('express');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const db = require('../config/db');

// 生成6位随机班级码
function generateClassCode() {
  return Math.random().toString(36).substr(2, 6).toUpperCase();
}

// 创建班级（仅限老师）
router.post('/', async (req, res) => {
  try {
    const { name } = req.body;
    const classCode = generateClassCode();
    const classId = uuidv4();

    // 创建班级
    await db.execute(
      'INSERT INTO classes (id, name, class_code, creator_id) VALUES (?, ?, ?, ?)',
      [classId, name, classCode, req.user.id]
    );

    // 将创建者添加为老师角色
    await db.execute(
      'INSERT INTO class_members (id, class_id, user_id, role) VALUES (?, ?, ?, ?)',
      [uuidv4(), classId, req.user.id, 'teacher']
    );

    res.json({
      id: classId,
      name,
      classCode
    });
  } catch (error) {
    res.status(500).json({ error: '创建班级失败' });
  }
});

// 加入班级（通过班级码）
router.post('/join', async (req, res) => {
  try {
    const { classCode } = req.body;

    // 查找班级
    const [classes] = await db.execute(
      'SELECT * FROM classes WHERE class_code = ?',
      [classCode]
    );

    if (classes.length === 0) {
      return res.status(404).json({ error: '班级码无效' });
    }

    const classId = classes[0].id;

    // 检查是否已经是班级成员
    const [members] = await db.execute(
      'SELECT * FROM class_members WHERE class_id = ? AND user_id = ?',
      [classId, req.user.id]
    );

    if (members.length > 0) {
      return res.status(400).json({ error: '已经是班级成员' });
    }

    // 添加为学生成员
    await db.execute(
      'INSERT INTO class_members (id, class_id, user_id, role) VALUES (?, ?, ?, ?)',
      [uuidv4(), classId, req.user.id, 'student']
    );

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: '加入班级失败' });
  }
});

// 获取班级信息
router.get('/:id', async (req, res) => {
  try {
    const [classes] = await db.execute(
      `SELECT c.*, cm.role 
       FROM classes c 
       JOIN class_members cm ON c.id = cm.class_id 
       WHERE c.id = ? AND cm.user_id = ?`,
      [req.params.id, req.user.id]
    );

    if (classes.length === 0) {
      return res.status(404).json({ error: '班级不存在或无权访问' });
    }

    res.json(classes[0]);
  } catch (error) {
    res.status(500).json({ error: '获取班级信息失败' });
  }
});